import {Component} from '@angular/core';
import {NavController, ViewController, ToastController, LoadingController} from 'ionic-angular';
import {FormBuilder, Validators, FormGroup} from '@angular/forms';

import {UserService} from "../../providers/UserService";
import {Login} from '../login/login'

import {STATUS_SUCCESS, STATUS_FAIL} from "../../providers/Constants";
import {JiGuanService} from "../../providers/JiGuanService";
import {BaseUI} from "../../common/baseui";

@Component({
  selector: 'page-signup',
  templateUrl: 'signup.html',
})
export class Signup extends BaseUI {
  signupForm: FormGroup;
  phone: any;
  password: any;
  confirmPassword: any;

  constructor(public navCtrl: NavController,
              public viewCtrl: ViewController,
              private formBuilder: FormBuilder,
              public loadingCtrl: LoadingController,
              private toastCtrl: ToastController,
              private userService: UserService,
              private jiGuanService: JiGuanService) {

    super();

    this.signupForm = formBuilder.group({
      phone: ['', Validators.compose([Validators.required, Validators.maxLength(11), Validators.minLength(11)])],
      password: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
      confirmPassword: ['', Validators.compose([Validators.required, Validators.minLength(6)])],
    })
    this.phone = this.signupForm.controls['phone'];
    this.password = this.signupForm.controls['password'];
    this.confirmPassword = this.signupForm.controls['confirmPassword'];

  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad Signup');
  }

  //关闭窗口
  dismiss() {
    this.viewCtrl.dismiss();
  }

  //注册
  register(value) {

    // 验证密码是否一致
    if (value.password != null && value.confirmPassword != value.password) {
      this.toastCtrl.create({message: "两次密码不一致", duration: 3000}).present();
      return false;
    }
    let loader = this.loadingCtrl.create({
      content: "正在注册...",
      duration: 3000,
    });
    loader.present();
    this.userService.regiseter(value).then(res => {

      if (res["status"] == STATUS_FAIL) {
        super.showToast(this.toastCtrl,res["msg"],'bottom');
        loader.dismiss();
        return false;
      }
      if (res["status"] == STATUS_SUCCESS) {//后台服务成功
        this.jiGuanService.register(value.phone, value.password).then(() => {//极光平台上注册(成功)
          loader.dismiss();
          this.toastCtrl.create({message: "注册成功,已跳转登陆!", duration: 4500}).present();
          this.navCtrl.push(Login, {
            phone: value.phone,
            password: value.password,
            page: "SignPage",
          });
        }).catch((error) => {  //极光IM注册失败
          loader.dismiss();
          super.showToast(this.toastCtrl, error.description, 'bottom');
        })
      }
    });

  }

}
